<script setup>
import SearchForm from '@/components/Search-Form.vue'
import { ref, watch } from 'vue'
import TableBase from '@/components/Table-Base.vue'
import TablePagination from '@/components/Table-Pagination.vue'
import DialogBase from '@/components/Dialog-Base.vue'
import { MessagePlugin } from 'tdesign-vue-next'
import {
    delPropertyItem,
    getCompanyList,
    getPropertyList,
    getBuildingList,
    getPaymentPrice,
    addPropertyItem
} from '@/api/property'
import MainContent from '@/components/Main-Content.vue'

const paymentMethodMap = {
    1: '微信',
    2: '支付宝',
    3: '现金'
}
const showDialog = ref(false)
const dialogType = ref('add')
const rules = ref({
    enterpriseId: [
        {
            required: true, message: '请选择企业', trigger: 'change'
        }
    ],
    buildingId: [
        {
            required: true, message: '请选择楼宇', trigger: 'change'
        }
    ],
    paymentDate: [
        {
            required: true, message: '请选择缴费周期', trigger: 'change'
        }
    ],
    paymentAmount: [
        {
            required: true, message: '请填写上述三项表单以获得支付金额', trigger: 'blur'
        }
    ],
    paymentMethod: [
        {
            required: true, message: '请选择支付方式', trigger: 'change'
        }
    ]
})
const dialogForm = ref({})
const companyList = ref([])
const buildingList = ref([])
const orderInfo = ref({})
const formData = ref({})
const searchCheckedDate = ref([])
const dialogCheckedDate = ref([])
const query = ref({
    page: 1,
    pageSize: 10
})
const listData = ref({
    list: [],
    total: 0
})
const columns = ref([
    {
        title: '序号',
        colKey: 'serial-number',
        width: 80
    },
    {
        title: '账单编号',
        colKey: 'billNumber',
        width: 180
    },
    {
        title: '企业名称',
        colKey: 'enterpriseName'
    },
    {
        title: '租赁楼宇',
        colKey: 'buildingName'
    },
    {
        title: '物业费（元/㎡）',
        colKey: 'propertyFeePrice'
    },
    {
        title: '账单金额（元）',
        colKey: 'paymentAmount'
    },
    {
        title: '缴费时间',
        colKey: 'createTime',
        width: 180
    },
    {
        title: '操作',
        colKey: 'option'
    }
])
const dialogFormInstance = ref(null)

const search = async () => {
    const res = await getPropertyList({
        ...query.value,
        ...formData.value,
        start: searchCheckedDate.value[0] || null,
        end: searchCheckedDate.value[1] || null
    })
    listData.value.list = res.data.rows.map(e => {
        e.status === 1 ? e.status = '租赁中' : e.status = '空置中'
        return e
    })
    listData.value.total = res.data.total
}
const reset = () => {
    formData.value = {}
    searchCheckedDate.value = []
    search()
}
const addProperty = async () => {
    dialogType.value = 'add'
    showDialog.value = true
    companyList.value = (await getCompanyList()).data
    buildingList.value = (await getBuildingList()).data
}
const closeDialog = () => {
    showDialog.value = false
    if (dialogFormInstance.value) dialogFormInstance.value.clearValidate()
}
const clickClose = () => {
    showDialog.value = false
    if (dialogFormInstance.value) dialogFormInstance.value.reset()
}
const dialogConfirm = async () => {
    const valid = await dialogFormInstance.value.validate()
    if (typeof valid === 'boolean' && valid) {
        const data = JSON.parse(JSON.stringify(dialogForm.value))
        delete data.paymentDate
        const res = await addPropertyItem(data)
        if (res.code !== 10000) return
        closeDialog()
        dialogFormInstance.value.reset()
        await MessagePlugin.success('添加成功！')
        await search()
    }
}
const datePickerChange = e => {
    dialogForm.value.startTime = e[0]
    dialogForm.value.endTime = e[1]
    dialogForm.value.paymentDate = e
    getPrice()
}
const getPrice = async () => {
    const form = dialogForm.value
    if (!form.buildingId) return
    if (!form.startTime) return
    if (!form.endTime) return

    dialogForm.value.paymentAmount = (await getPaymentPrice({
        buildingId: form.buildingId,
        startTime: form.startTime,
        endTime: form.endTime
    })).data
}
const getRow = async (data, type) => {
    if (type === 'view') {
        orderInfo.value = data.row
        dialogType.value = 'view'
        showDialog.value = true
    } else {
        const res = await delPropertyItem(data.row.id)
        if (res.code === 10000) {
            await MessagePlugin.success('删除成功!')
            if (listData.value.list.length === 1 && query.value.page > 1) query.value.page--
            await search()
        } else {
            await MessagePlugin.error(res.msg)
        }
    }
}
const changePage = e => {
    query.value.page = e.current
    query.value.pageSize = e.pageSize
    search()
}

watch(dialogForm, () => getPrice(), { deep: true })

search()
</script>

<template>
    <main-content>
        <search-form>
            <t-form
                ref="form"
                :data="formData"
                label-width="auto"
                layout="inline"
            >
                <t-form-item label="楼宇名称">
                    <t-input v-model.trim="formData.name" placeholder="请输入楼宇名称"></t-input>
                </t-form-item>
                <t-form-item label="缴费时间">
                    <t-date-range-picker allow-input clearable
                                         :placeholder="['开始日期', '结束日期']"
                                         v-model="searchCheckedDate"/>
                </t-form-item>
                <t-form-item style="min-width: auto">
                    <t-button @click="search" type="submit" style="margin-right: 10px;">查询</t-button>
                    <t-button @click="reset" variant="outline">重置</t-button>
                </t-form-item>
            </t-form>
        </search-form>

        <table-base :columns="columns" :list="listData.list">
            <template #top-btn>
                <t-button theme="primary" @click="addProperty">添加账单</t-button>
            </template>
            <template #option-table="row">
                <t-button variant="text" theme="primary" @click="getRow(row, 'view')">查看</t-button>
                <t-popconfirm
                    destroyOnClose
                    showArrow
                    @confirm="getRow(row, 'del')"
                    theme="warning" content="确认删除吗">
                    <t-button variant="text" theme="primary">删除</t-button>
                </t-popconfirm>
            </template>
        </table-base>

        <table-pagination :total="listData.total" @changePage="changePage"></table-pagination>

        <dialog-base :showDialog="showDialog"
                     :dialogType="dialogType"
                     :dialogTitle="dialogType === 'add' ? '添加账单' : '查看账单'"
                     @dialogConfirm="dialogConfirm"
                     @clickClose="clickClose"
                     @closeDialog="closeDialog">
            <t-form class="dialogForm" ref="dialogFormInstance" labelAlign="top"
                    :rules="rules" :data="dialogForm" v-if="dialogType === 'add'">
                <t-form-item label="选择租户" name="enterpriseId">
                    <t-select
                        filterable
                        placeholder="请选择租户"
                        v-model.trim="dialogForm.enterpriseId"
                        showArrow>
                        <t-option v-for="e in companyList" :key="e.id" :label="e.name" :value="e.id"/>
                    </t-select>
                </t-form-item>
                <t-form-item label="租赁楼宇" name="buildingId">
                    <t-select
                        filterable
                        placeholder="请选择租赁楼宇"
                        v-model.trim="dialogForm.buildingId"
                        showArrow>
                        <t-option v-for="e in buildingList" :key="e.id" :label="e.name" :value="e.id"/>
                    </t-select>
                </t-form-item>
                <t-form-item label="缴费周期" name="paymentDate">
                    <t-date-range-picker allow-input clearable
                                         :placeholder="['开始日期', '结束日期']"
                                         v-model="dialogCheckedDate"
                                         @change="datePickerChange"/>
                </t-form-item>
                <t-form-item label="支付金额" name="paymentAmount">
                    <t-input placeholder="完成上列表单查看金额" :value="dialogForm.paymentAmount" disabled/>
                </t-form-item>
                <t-form-item label="支付方式" name="paymentMethod">
                    <t-select
                        placeholder="请选择支付方式"
                        v-model.trim="dialogForm.paymentMethod"
                        showArrow>
                        <t-option key="1" label="微信" value="1"/>
                        <t-option key="2" label="支付宝" value="2"/>
                        <t-option key="3" label="现金" value="3"/>
                    </t-select>
                </t-form-item>
            </t-form>
            <div v-else class="order-info">
                <div>
                    <span>租户名称：</span>
                    <span>{{ orderInfo.enterpriseName }}</span>
                </div>
                <div>
                    <span>租赁楼宇：</span>
                    <span>{{ orderInfo.buildingName }}</span>
                </div>
                <div>
                    <span>账单编号：</span>
                    <span>{{ orderInfo.billNumber }}</span>
                </div>
                <div>
                    <span>缴费周期：</span>
                    <span>{{ orderInfo.startTime }} 至 {{ orderInfo.endTime }}</span>
                </div>
                <div>
                    <span>物业费（元/㎡）：</span>
                    <span>{{ orderInfo.propertyFeePrice }}</span>
                </div>
                <div>
                    <span>账单金额（元）：</span>
                    <span>{{ orderInfo.paymentAmount }}</span>
                </div>
                <div>
                    <span>支付方式：</span>
                    <span>{{ paymentMethodMap[orderInfo.paymentMethod] }}</span>
                </div>
                <div>
                    <span>缴费时间：</span>
                    <span>{{ orderInfo.createTime }}</span>
                </div>
            </div>
        </dialog-base>
    </main-content>
</template>

<style scoped lang="scss">
:deep .t-dialog {
    width: 450px;

    .order-info {
        > div {
            height: 40px;
            line-height: 40px;

            span:first-child {
                color: var(--td-text-color-secondary);
            }

            span:last-child {
                color: var(--td-text-color-primary);
                font-weight: 500;
            }
        }
    }
}
</style>
